<template>
    <div class="fix-width-frame">
        <div class='tip'>
            <span>菜鸟-义乌-百世 仓库地址：</span>浙江省金华市义乌市北苑街道凌云2区
        </div>
        <div class='tip'>
            <span>菜鸟-泉州-申通 仓库地址：</span>福建省泉州市石狮市灵秀镇海西电子商务园
        </div>
        <div class="add_container">
            <el-row type="flex" align="middle" style="margin-bottom: 10px;">
                <el-col :span="4">
                    <span>发货地区</span>
                </el-col>
				        <el-col :span="20"> 
                    <el-select
                      v-model="sheng"
                      @change="choseProvince"
                      placeholder="省级地区">
                      <el-option
                        v-for="item in province"
                        :key="item.id"
                        :label="item.value"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-select
                      v-model="shi"
                      @change="choseCity"
                      placeholder="市级地区">
                      <el-option
                        v-for="item in shi1"
                        :key="item.id"
                        :label="item.value"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-select
                      v-model="qu"
                      @change="choseBlock"
                      placeholder="区级地区">
                      <el-option
                        v-for="item in qu1"
                        :key="item.id"
                        :label="item.value"
                        :value="item.value">
                       </el-option>
                    </el-select>
                </el-col>
            </el-row>
            <el-row type="flex" align="middle" style="margin-bottom: 10px;">
                <el-col :span="4">
                    <span>详细地址（<span style="color: red">*</span>必填）</span>
                </el-col>
                <el-col :span="17">
                    <el-input v-model="detail" placeholder="详细地址" label="详细地址"></el-input>
                </el-col>
            </el-row>
            <el-row :gutter="10" type="flex" align="middle" style="margin-bottom: 10px;">
                <el-col :span="4">
                    <span>发货人姓名（<span style="color: red">*</span>必填）</span>
                </el-col>
                <el-col :span="8">
                    <el-input v-model="name" placeholder="姓名" label="发货人姓名" class="input"></el-input>
                </el-col>
                <el-col :span="4">
                    <span>发货人电话（<span style="color: red">*</span>必填）</span>
                </el-col>
                <el-col :span="8">
                    <el-input v-model="tel" placeholder="电话" label="发货人电话" class="input"></el-input>
                </el-col>
              </el-row>  
              <el-row type="flex" justify="end" style="margin-bottom: 10px;">
                <el-col :span="24">
                  <el-button type="primary" @click="addNewAddress()">添加地址</el-button>
                </el-col>
              </el-row>
        </div>
        <div class="table_container">
          <el-table
                v-loading="tableLoading"
                :data="tableData"
                style="width: 100%">
                <el-table-column 
                    type="index"
                    width="100">
                </el-table-column>
                <el-table-column label="地址">
                  <template slot-scope="scope">
                    <div v-show="scope.$index == editedRow">
                      <el-row type="flex" align="middle" style="margin-bottom: 10px;">
                        <el-col :span="4">
                            <span>发货地区</span>
                        </el-col>
                        <el-col :span="20"> 
                            <el-select
                              v-model="editedRowInfo.province"
                              @change="choseProvince"
                              placeholder="省级地区">
                              <el-option
                                v-for="item in province"
                                :key="item.id"
                                :label="item.value"
                                :value="item.value">
                              </el-option>
                            </el-select>
                            <el-select
                              v-model="editedRowInfo.city"
                              @change="choseCity"
                              placeholder="市级地区">
                              <el-option
                                v-for="item in shi1"
                                :key="item.id"
                                :label="item.value"
                                :value="item.value">
                              </el-option>
                            </el-select>
                            <el-select
                              v-model="editedRowInfo.region"
                              @change="choseBlock"
                              placeholder="区级地区">
                              <el-option
                                v-for="item in qu1"
                                :key="item.id"
                                :label="item.value"
                                :value="item.value">
                              </el-option>
                            </el-select>
                        </el-col>
                    </el-row>
                    <el-row type="flex" align="middle" style="margin-bottom: 10px;">
                        <el-col :span="4">
                            <span>详细地址（<span style="color: red">*</span>必填）</span>
                        </el-col>
                        <el-col :span="17">
                            <el-input v-model="editedRowInfo.detail" placeholder="详细地址" label="详细地址"></el-input>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10" type="flex" align="middle" style="margin-bottom: 10px;">
                        <el-col :span="4">
                            <span>发货人姓名（<span style="color: red">*</span>必填）</span>
                        </el-col>
                        <el-col :span="8">
                            <el-input v-model="editedRowInfo.name" placeholder="姓名" label="发货人姓名" class="input"></el-input>
                        </el-col>
                        <el-col :span="4">
                            <span>发货人电话（<span style="color: red">*</span>必填）</span>
                        </el-col>
                        <el-col :span="8">
                            <el-input v-model="editedRowInfo.tel" placeholder="电话" label="发货人电话" class="input"></el-input>
                        </el-col>
                      </el-row>  
                    </div>
                    <div v-show="scope.$index != editedRow">
                    {{`${scope.row.name}; ${scope.row.tel}; ${scope.row.province} ${scope.row.city} ${scope.row.region} ${scope.row.detail}`}}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="编辑" width="150">
                    <template slot-scope="scope">
                      <el-button size="small" type="primary" @click="handleEdit(scope.$index)" v-if="scope.$index != editedRow">编辑</el-button>
                      <el-button size="small" type="primary" @click="handleEditOk(scope.$index)" v-if="scope.$index == editedRow">确定</el-button>
                      <el-button size="small" type="primary" @click="handleEditCancel(scope.$index)" v-if="scope.$index == editedRow">取消</el-button>
                  </template>
                </el-table-column>
            </el-table>
            <div class="Pagination" style="text-align: left;margin-top: 10px;">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-size="limit"
                  layout="total, prev, pager, next"
                  :total="count">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
    import headTop from '@/components/headTop'
    import {getAllAddress, addAddress, updateAddress} from '@/api/address'
    import axios from 'axios'
    export default {
      data () {
        return {
          tel: '',
          name: '',
          detail: '',
          tableData: [],
          currentRow: null,
          offset: 0,
          limit: 20,
          count: 0,
          currentPage: 1,
          mapJson: '../static/map.json',
          province: '',
          sheng: '',
          shi: '',
          shi1: [],
          qu: '',
          qu1: [],
          city: '',
          block: '',
          editedRow: -1,
          editedRowInfo: {
            name: '',
            tel: '',
            province: '',
            city: '',
            region: '',
            detail: ''
          },
          tableLoading: false,
          fullscreenLoading: false
        }
      },
      components: {
        headTop
      },
      created () {
        // this.initData();
        this.getCityData()
        this.getAddress()
      },
      methods: {
        async addNewAddress () {
          let p = this.sheng.trim()
          if (p.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let c = this.shi.trim()
          if (c.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let d = this.qu.trim()
          if (d.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let n = this.name.trim()
          if (n.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let t = this.tel.trim()
          if (t.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }
          const loading = this.$loading({
            lock: true,
            text: '正在加载',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // const result = await addAddress(`${n}; ${t}; ${p} ${c} ${d} ${this.detail}`)
          const result = await addAddress({
            name: n,
            tel: t,
            province: p,
            city: c,
            region: d,
            detail: this.detail,
            address: ''
          })
          if (result.status === 200) {
            if (result.data.code === 200) {
              if (this.currentPage === 1) {
                this.getAddress()
              }
              this.editedRow = -1
            } else {

            }
          }
          loading.close()
        },
        async getAddress () {
          this.tableLoading = true
          try {
            const result = await getAllAddress(this.currentPage, this.limit)
            if (result.status === 200 && result.data.code === 200) {
              this.tableData = result.data.data
              this.count = result.data.data.length
            } else {
              throw new Error('获取数据失败')
            }
          } catch (err) {
            // this.$message.error('列表获取失败')
            console.log('获取数据失败', err)
          }
          this.tableLoading = false
        },
        async initData () {
    
        },
        handleSizeChange (size) {
          this.limit = size
          this.getAddress()
        },
        handleCurrentChange (page) {
          this.currentPage = page
          this.getAddress()
        },

        handleEdit (row) {
          this.editedRow = row
          // let fullAddress = this.tableData[row].address
          // if (fullAddress !== '') {
          //   let components = fullAddress.split(';').map(x => x.trim())
          //   let name = components[0]
          //   let tel = components[1]
          //   let address = components[2].split(' ').map(x => x.trim())
          //   this.editedRowInfo = {
          //     name: name,
          //     tel: tel,
          //     province: address[0],
          //     city: address[1],
          //     region: address[2],
          //     detail: address[3]
          //   }
          // } else {
          this.editedRowInfo = this.tableData[row]
          // }
        },

        async handleEditOk (row) {
          let p = this.editedRowInfo.province.trim()
          if (p.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let c = this.editedRowInfo.city.trim()
          if (c.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let d = this.editedRowInfo.region.trim()
          if (d.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let n = this.editedRowInfo.name.trim()
          if (n.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }

          let t = this.editedRowInfo.tel.trim()
          if (t.length === 0) {
            this.$message.error('请输入有效地址')
            return
          }
          try {
            const addr = `${n}; ${t}; ${p} ${c} ${d} ${this.editedRowInfo.detail}`
    
            // const result = await updateAddress(this.tableData[row].id, addr)
            const result = await updateAddress(this.tableData[row].id, {
              name: n,
              tel: t,
              province: p,
              city: c,
              region: d,
              detail: this.editedRowInfo.detail,
              address: ''
            })
            if (result.status === 200 && result.data.code === 200) {
              this.tableData[row].address = addr
              this.editedRow = -1
            } else {
              throw new Error('获取数据失败')
            }
          } catch (err) {
            // this.$message.error('更新地址失败')
            console.log('获取数据失败', err)
          }
        },

        handleEditCancel (row) {
          this.editedRow = -1
        },
        // 加载china地点数据，三级
        getCityData: function () {
          let that = this
          axios.get(this.mapJson).then(function (response) {
            if (response.status === 200) {
              let data = response.data
              that.province = []
              that.city = []
              that.block = []
              // 省市区数据分类
              for (let item in data) {
                if (item.match(/0000$/)) { // 省
                  that.province.push({id: item, value: data[item], children: []})
                } else if (item.match(/00$/)) { // 市
                  that.city.push({id: item, value: data[item], children: []})
                } else { // 区
                  that.block.push({id: item, value: data[item]})
                }
              }
              // 分类市级
              for (let index in that.province) {
                for (let index1 in that.city) {
                  if (that.province[index].id.slice(0, 2) === that.city[index1].id.slice(0, 2)) {
                    that.province[index].children.push(that.city[index1])
                  }
                }
              }
              // 分类区级
              for (let item1 in that.city) {
                for (let item2 in that.block) {
                  if (that.block[item2].id.slice(0, 4) === that.city[item1].id.slice(0, 4)) {
                    that.city[item1].children.push(that.block[item2])
                  }
                }
              }
            } else {
              console.log(response.status)
            }
          }).catch(function (error) { console.log(typeof +error) })
        },
        // 选省
        choseProvince: function (e) {
          for (let index2 in this.province) {
            if (e === this.province[index2].value) {
              this.shi1 = this.province[index2].children
              this.shi = this.province[index2].children[0].value
              this.qu1 = this.province[index2].children[0].children
              this.qu = this.province[index2].children[0].children[0].value
              this.E = this.qu1[0].id
            }
          }
        },
        // 选市
        choseCity: function (e) {
          for (let index3 in this.city) {
            if (e === this.city[index3].value) {
              this.qu1 = this.city[index3].children
              this.qu = this.city[index3].children[0].value
              this.E = this.qu1[0].id
            // console.log(this.E)
            }
          }
        },
        // 选区
        choseBlock: function (e) {
          this.E = e
          // console.log(this.E)
        }
      }
}
</script>

<style lang="less" scoped>
  @import '../../style/mixin';
  .fix-width-frame {
    margin: 0 auto;
    width: 1000px;
  }
  .table_container{
      padding: 20px 0;
  }
  .add_container {
      margin-top: 20px;
      padding: 10px 20px;
      border: 1px solid @bc;
  }
  .input {
      width: 220px;
  }

  .el-row {
    font-size: 12px;
    color: #222;
  }
  .tip {
        color: #555;
        font-size: 12px;
        margin-top: 20px;
        // margin-left: 20px;
  }
  .tip span {
        color: #f82a0f;
        // font-weight: bold;
  }
</style>
